package com.xjg.jms;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;

import com.xjg.dao.LoginPushRecordDao;
import com.xjg.dao.OffLineMessageDao;
import com.xjg.domain.LoginPushRecord;
import com.xjg.domain.MessageInfo;
import com.xjg.domain.OffLineMessage;
import com.xjg.dynconfig.PushConfigs;

public class MsgListener {
	private static Logger logger = LoggerFactory.getLogger(MsgListener.class);
	@Autowired
	private LoginPushRecordDao loginPushRecordDao;
	@Autowired
	private PushConfigs pushConfigs;
	@Autowired
	private OffLineMessageDao offLineMessageDao;
	@Autowired
	private JmsTemplate jmsTemplate;
	public void onMessage(MessageInfo message) {
		logger.info("recevice message:"+message);
		try{
			//查询目的用户所在push服务器
			LoginPushRecord record = loginPushRecordDao.getRecordByUserid(message.getTo());
			//判断用户是否在线 record不为空说明用户在线
			if(record!=null){
				dealOnLineMessage(message,record.getServerIp());
			}else{
				//做离线存储
				logger.info("LoginPushRecord is null");
				dealOffLineMsg(message);
				
			}
		}catch(Exception e){
			logger.error("发送消息失败："+message,e);
		}
		
	}
	private void dealOffLineMsg(MessageInfo message){
		OffLineMessage olm = offLineMessageDao.getOffLineMessageByUserid(message.getTo());
		if(olm==null){
			olm = new OffLineMessage();
		}
		olm.setUserid(message.getTo());
		//需增加消息条数限制
		if("im".equals(message.getType())){
			olm.getImMessages().add(message);
			//超过20条删除第一条
			if(olm.getImMessages().size()>=30){
				olm.getImMessages().remove(0);
			}
			olm.setImMsgCount(olm.getImMessages().size());
		}else if("push".equals(message.getType())){
			olm.getPushMessages().add(message);
			//超过两条删除第一条
			if(olm.getPushMessages().size()>2){
				olm.getPushMessages().remove(0);
			}
			olm.setPushMsgCount(olm.getPushMessages().size());
		}
		this.offLineMessageDao.save(olm);
	}
	private void dealOnLineMessage(MessageInfo message,String serverIp){
		//根据push服务器地址获取消息队列名
		String queue = pushConfigs.getQueueByServer(serverIp);
		logger.info("send message queue:"+queue);
		//将消息发往指定队列中
		jmsTemplate.convertAndSend(queue, message);
	}
}
